<template>
  <van-icon
    :color="attitude === 1 ? '#ff0000' : '#777'"
    :name="attitude === 1 ? 'good-job' : 'good-job-o'"
    :loading="likeLoading"
    @click="onLike"
  />
</template>

<script>
import { addlikeAPI, deleteLikeAPI } from '../../../api/index.js'
export default {
  name: 'LikeArticle',
  props: {
    attitude: { // -1 无态度， 1 点赞
      type: Number,
      default: -1
    },
    articleId: {
      type: String,
      default: ''
    }
  },

  data () {
    return {
      likeLoading: false // 点赞加载状态
    }
  },

  methods: {
    // 点赞、取消点赞文章
    async onLike () {
      // 定义一个提示变量 - 为什么要把这个变量创在try的外面
      let massage = '操作成功'
      try {
        // 调用接口前开启加载
        this.likeLoading = true

        if (this.attitude === 1) {
          // 已点赞，需要取消点赞
          await deleteLikeAPI(this.articleId)
          massage = '取消点赞成功'
        } else {
          // 未点赞，需要添加点赞
          await addlikeAPI({
            target: this.articleId
          })
          massage = '点赞成功'
        }

        this.$emit('update:attitude', this.attitude === 1 ? -1 : 1)

        this.$toast.success(massage)
      } catch (error) {
        console.log(error)
        massage = '网络异常，请稍后重试。'
        this.$toast.fail(massage)
      }

      // 无论成功还是失败都需要关闭加载状态
      this.likeLoading = false
    }
  }
}
</script>

<style>

</style>
